package com.uetoken.cn.activity;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.ShippingAddressBean;
import com.uetoken.cn.bean.area.CityBean;
import com.uetoken.cn.bean.area.DistrictBean;
import com.uetoken.cn.bean.area.ProvinceBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.AreaUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 新增收货地址
 */
public class NewShippingAddressActivity extends BaseActivity implements WebResponse{

    @BindView(R.id.iv_back)
    ImageView      mIvBack;
    @BindView(R.id.tv_title)
    TextView       mTvTitle;
    @BindView(R.id.rl_activity_new_shipping_address_select_area)
    RelativeLayout mRlSelectArea;
    @BindView(R.id.tv_activity_new_shipping_address_select_area)
    TextView       mTvSelectArea;
    @BindView(R.id.edt_activity_new_shipping_address_input_address)
    EditText       mEdtInputAddress;
    @BindView(R.id.edt_activity_new_shipping_address_input_name)
    EditText       mEdtInputName;
    @BindView(R.id.edt_activity_new_shipping_address_input_phone)
    EditText       mEdtInputPhone;
    @BindView(R.id.cb_activity_new_shipping_address_default)
    CheckBox       mCbDefault;
    @BindView(R.id.tv_activity_new_shipping_address_delete_address)
    TextView       mTvDeleteAddress;
    @BindView(R.id.tv_activity_new_shipping_address_delete_save_address)
    TextView mTvSave;

    private OptionsPickerView mPickerView;
    /**
     * 获取省市区列表
     */
    private static final int  NETWORK_REQUEST_AREA = 10;

    /**
     * 删除地址
     */
    private static final int NETWORK_REQUEST_DETELE_ADDRESS = 20;

    /**
     * 创建或者设置默认地址
     */
    private static final int  NETWORK_REQUEST_CREATE_OR_SETTING_DEFAULT_ADDRESS = 30;
    /**
     * 省
     */
    private ArrayList<String> provinceItems = new ArrayList<>();
    /**
     * 市
     */
    private ArrayList<ArrayList<String>> cityItems = new ArrayList<>();
    /**
     * 区
     */
    private ArrayList<ArrayList<ArrayList<String>>> areaItems = new ArrayList<>();

    private List<ProvinceBean> mProvinceBeanList = new ArrayList<>();
    private ThreadUtils.SimpleTask<Void> task;
    /**
     * 存储在本地的地址
     */
    private String areas;
    /**
     * 用户所选区的id
     */
    private int seLectAreaId;
    /**
     * 服务器返回的地址主键值(删除地址需要传入此值)
     */
    private int consigneeid = 0;


    @Override
    public int getLayoutId() {
        return R.layout.activity_new_shipping_address;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);

        mIvBack.setVisibility(View.VISIBLE);
        mTvTitle.setText(getResources().getString(R.string.str_new_shipping_address));

        mPickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                LogUtils.e(provinceItems.get(options1),mProvinceBeanList.get(options1).getAreaid());
                LogUtils.e(cityItems.get(options1).get(options2),mProvinceBeanList.get(options1).getCityBeans().get(options2).getAreaid());
                LogUtils.e(areaItems.get(options1).get(options2).get(options3),mProvinceBeanList.get(options1).getCityBeans().get(options2).getDistrictBeans().get(options3).getAreaid());
                //选中的第一级的areadid
                int firstAreadid = mProvinceBeanList.get(options1).getAreaid();
                //选中的第二级的areadid
                int secondAreaid = mProvinceBeanList.get(options1).getCityBeans().get(options2).getAreaid();
                //选中的第三级级的areadid
                int thirdAreaid = mProvinceBeanList.get(options1).getCityBeans().get(options2).getDistrictBeans().get(options3).getAreaid();

                if (firstAreadid==secondAreaid){
                    //说明只有一级数据
                    seLectAreaId = firstAreadid;
                    mTvSelectArea.setText(provinceItems.get(options1));
                }else if (secondAreaid==thirdAreaid){
                    //说明只有两级数据
                    seLectAreaId = secondAreaid;
                    mTvSelectArea.setText(provinceItems.get(options1)+cityItems.get(options1).get(options2));
                }else{
                    //有三级数据
                    seLectAreaId = thirdAreaid;
                    mTvSelectArea.setText(provinceItems.get(options1)+cityItems.get(options1).get(options2)+areaItems.get(options1).get(options2).get(options3));
                }
            }
        }).build();

    }


    @Override
    public void initData() {
        Intent intent = getIntent();
        String address = intent.getStringExtra("address");
        if (address.equals("have")) {
            //从用户地址界面点击item跳转过来的
            ShippingAddressBean.DataBean dataBean = (ShippingAddressBean.DataBean) intent.getSerializableExtra("info");
            mTvSelectArea.setText(dataBean.getProductname() + dataBean.getCityname() + dataBean.getRegionname());
            mEdtInputAddress.setText(dataBean.getAddress());
            mEdtInputName.setText(dataBean.getConsigneename());
            mEdtInputPhone.setText(dataBean.getMobileno());
            mTvDeleteAddress.setVisibility(View.VISIBLE);

            seLectAreaId = dataBean.getRegionid();
            consigneeid = dataBean.getConsigneeid();
        } else {
            //从用户地址点击新增地址跳转过来的
            mTvDeleteAddress.setVisibility(View.GONE);
        }

        areas = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_AREAS_INFO).getString(Constant.SP_AREA, "");
        if (TextUtils.isEmpty(areas)) {
            showLoading();
            OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getAreaUrl(), NETWORK_REQUEST_AREA, Params.getAreaParams());
        }else{
            showLoading();
            parseData(areas);
            ThreadUtils.executeByIo(task);
        }
    }

    @Override
    public void init() {

    }


    @OnClick({R.id.iv_back, R.id.rl_activity_new_shipping_address_select_area,R.id.tv_activity_new_shipping_address_delete_address,R.id.tv_activity_new_shipping_address_delete_save_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_activity_new_shipping_address_select_area:
                //隐藏软键盘
                KeyboardUtils.hideSoftInput(this);
                if (mProvinceBeanList.size()!=0){
                    mPickerView.show();
                }else {
                    ToastUtils.showShort(getResources().getString(R.string.str_area_data_not_loading_finish));
                }
                break;
            case R.id.tv_activity_new_shipping_address_delete_address:
                deleteAddress();
                break;
            case R.id.tv_activity_new_shipping_address_delete_save_address:
                saveAddress();
                break;

        }
    }

    /**
     * 删除地址
     */
    private void deleteAddress() {
        new QMUIDialog.MessageDialogBuilder(this).setTitle(getResources().getString(R.string.str_delete_address_title)).setMessage(getResources().getString(R.string.str_delete_address_message))
                .addAction(getResources().getString(R.string.str_cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                }).addAction(getResources().getString(R.string.str_confirm), new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
                showLoading();
                OkHttpUtils.getInstance().getStringWithParam(NewShippingAddressActivity.this,ApiHelper.getDeleteShippingAddressUrl(),NETWORK_REQUEST_DETELE_ADDRESS,
                        Params.getDeleteShippingAddressParams(String.valueOf(consigneeid)));
            }
        }).show();

    }

    /**
     * 保存或修改地址
     */
    private void saveAddress() {
        //选择的区
        String approximateAddress = mTvSelectArea.getText().toString();
        //详细地址
        String detailAddress = mEdtInputAddress.getText().toString();
        //收货人
        String shippingName = mEdtInputName.getText().toString();
        //手机号
        String phone = mEdtInputPhone.getText().toString().trim();
        //是否设置为默认地址
        String isDefault;
        if (mCbDefault.isChecked()){
            //设置为默认地址传1否则传0
            isDefault = "1";
        }else{
            isDefault = "0";
        }
        if (TextUtils.isEmpty(approximateAddress)){
            ToastUtils.showShort(getResources().getString(R.string.str_please_select_area));
            return;
        }
        if (TextUtils.isEmpty(detailAddress)){
            ToastUtils.showShort(getResources().getString(R.string.str_detail_address));
            return;
        }
        if (TextUtils.isEmpty(shippingName)){
            ToastUtils.showShort(getResources().getString(R.string.str_shipping_name_not_empty));
            return;
        }
        if (TextUtils.isEmpty(phone)){
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)){

            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this,ApiHelper.getCreateOrSettingDefaultAddressUrl(),NETWORK_REQUEST_CREATE_OR_SETTING_DEFAULT_ADDRESS,
                Params.getCreateOrSettingDefaultAddressParams(String.valueOf(seLectAreaId),detailAddress,shippingName,phone,String.valueOf(consigneeid),"",isDefault));
    }


    @Override
    public void onSuccessResponse(Call call, final String response, int requestCode) throws IOException {
        JsonObject obj = new JsonParser().parse(response).getAsJsonObject();
        String message = obj.get("message").getAsString();
        int result = obj.get("result").getAsInt();

        switch (requestCode){
            case NETWORK_REQUEST_AREA:
                if (result > 0) {
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_AREAS_INFO).put(Constant.SP_AREA, response);
                    parseData(response);
                    ThreadUtils.executeByIo(task);
                }else{
                    dissmissDialog();
                }
                break;
            case NETWORK_REQUEST_DETELE_ADDRESS:
                dissmissDialog();
                if (result>0){
                    ToastUtils.showShort(message);
                    setResult(RESULT_OK);
                    finish();
                }else{
                    ToastUtils.showShort(message);
                }
                break;
            case NETWORK_REQUEST_CREATE_OR_SETTING_DEFAULT_ADDRESS:
                dissmissDialog();
                if (result>0){
                    ToastUtils.showShort(message);
                    setResult(RESULT_OK);
                    finish();
                }else{
                    ToastUtils.showShort(message);
                }
                break;
        }

    }

    /**
     * 遍历数据
     * @param response 存储在本地或者服务器返回的数据
     */
    private void parseData(final String response){
        //开启一个线程池去遍历数据
        task = new ThreadUtils.SimpleTask<Void>() {
            @Nullable
            @Override
            public Void doInBackground() throws Throwable {
                mProvinceBeanList = AreaUtils.parseAreaData(response);
                initPickerViewData();
                return null;
            }

            @Override
            public void onSuccess(@Nullable Void result) {
                dissmissDialog();
                mPickerView.setPicker(provinceItems,cityItems,areaItems);
            }
        };
    }


    /**
     * 初始化地址选择控件所需要的数据
     */
    private void initPickerViewData() {

        for (ProvinceBean provinceBean : mProvinceBeanList) {
            //该省的城市列表（第二级）
            ArrayList<String> cityList = new ArrayList<>();
            //该省的所有地区列表（第三级）
            ArrayList<ArrayList<String>> provinceAreaList = new ArrayList<>();

            for (CityBean cityBean : provinceBean.getCityBeans()) {

                cityList.add(cityBean.getAreaname());

                ArrayList<String> cityAreaList = new ArrayList<>();
                for (DistrictBean districtBean : cityBean.getDistrictBeans()) {
                    cityAreaList.add(districtBean.getAreaname());
                }

                provinceAreaList.add(cityAreaList);
            }

            provinceItems.add(provinceBean.getAreaname());
            cityItems.add(cityList);
            areaItems.add(provinceAreaList);
        }
    }


    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }


    @Override
    protected void onDestroy() {
        if (task!=null){
            task.cancel();
        }
        super.onDestroy();
    }
}
